$(function () {

    let top_list = [0]
    let $con = $(".content")
    let $list = $(".flex_right li")
    let t = null
    let animate = false

    $.each($con, function (index, ele) {

        top_list.push($(ele).offset().top) 

    })

    $list.click(function () {
        animate = true
        $(this).addClass("active").siblings().removeClass("active")
        let index = $(this).index(".flex_right li")
        changeTop(index + 1)
    })
    $(".return").click(function(){

        $("html,body")
        .stop()
        .animate({
            scrollTop: 0
        }, function () {
            animate = false
        })
    })

    function changeTop(index) {
        $("html,body")
            .stop()
            .animate({
                scrollTop: top_list[index] - 250
            }, function () {
                animate = false
            })

    }

    //页面滚动的时候改变样式
    $(window).scroll(function () {
        let scrollTop = $("html,body").scrollTop()
        if (!animate) {

            if (typeof t === "number") {
                return false
            }
            if(scrollTop > 500){
                t = setTimeout(() => {
                    let index = getIndex()
                    $list.eq(index).addClass("active").siblings().removeClass("active")
                    t = null
                }, 100);
            }else{
                $list.removeClass("active")
            }

        }

    })

    function getIndex() {


        let scrollTop = $("html,body").scrollTop()

        if (scrollTop >= top_list[top_list.length - 1]) {
            return top_list.length - 1
        }
        for (let i = 0; i < top_list.length; i++) {
            if (scrollTop >= top_list[i] && scrollTop < top_list[i + 1]) {
                return i
            }
        }


    }

})